﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.MountAndBlade.View.MissionViews.MissionMainAgentController
// Assembly: TaleWorlds.MountAndBlade.View, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 61152EB8-513B-4D4A-8AC0-0D1465C6CF6C
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\Modules\Native\bin\Win64_Shipping_Client\TaleWorlds.MountAndBlade.View.dll

using NetworkMessages.FromClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using TaleWorlds.Core;
using TaleWorlds.Engine;
using TaleWorlds.Engine.Options;
using TaleWorlds.InputSystem;
using TaleWorlds.Library;
using TaleWorlds.MountAndBlade.Network.Messages;

#nullable disable
namespace TaleWorlds.MountAndBlade.View.MissionViews
{
  [DefaultView]
  public class MissionMainAgentController : MissionView
  {
    private const float _minValueForAimStart = 0.2f;
    private const float _maxValueForAttackEnd = 0.6f;
    private float _lastForwardKeyPressTime;
    private float _lastBackwardKeyPressTime;
    private float _lastLeftKeyPressTime;
    private float _lastRightKeyPressTime;
    private float _lastWieldNextPrimaryWeaponTriggerTime;
    private float _lastWieldNextOffhandWeaponTriggerTime;
    private bool _activated = true;
    private bool _strafeModeActive;
    private bool _autoDismountModeActive;
    private bool _isPlayerAgentAdded;
    private bool _isPlayerAiming;
    private bool _playerShotMissile;
    private bool _isPlayerOrderOpen;
    private bool _isTargetLockEnabled;
    private Agent.MovementControlFlag _lastMovementKeyPressed = Agent.MovementControlFlag.Forward;
    private Agent _lockedAgent;
    private Agent _potentialLockTargetAgent;
    private float _lastLockKeyPressTime;
    private float _lastLockedAgentHeightDifference;
    public readonly MissionMainAgentInteractionComponent InteractionComponent;
    public bool IsChatOpen;
    private bool _weaponUsageToggleRequested;

    public event MissionMainAgentController.OnLockedAgentChangedDelegate OnLockedAgentChanged;

    public event MissionMainAgentController.OnPotentialLockedAgentChangedDelegate OnPotentialLockedAgentChanged;

    public bool IsDisabled { get; set; }

    public Vec3 CustomLookDir { get; set; }

    public bool IsPlayerAiming
    {
      get
      {
        if (this._isPlayerAiming)
          return true;
        if (this.Mission.MainAgent == null)
          return false;
        bool flag1 = false;
        bool flag2 = false;
        bool flag3 = false;
        if (this.Input != null)
          flag2 = this.Input.IsGameKeyDown(9);
        if (this.Mission.MainAgent != null)
        {
          MissionWeapon wieldedWeapon = this.Mission.MainAgent.WieldedWeapon;
          if (wieldedWeapon.CurrentUsageItem != null)
          {
            wieldedWeapon = this.Mission.MainAgent.WieldedWeapon;
            int num;
            if (!wieldedWeapon.CurrentUsageItem.IsRangedWeapon)
            {
              wieldedWeapon = this.Mission.MainAgent.WieldedWeapon;
              num = wieldedWeapon.CurrentUsageItem.IsAmmo ? 1 : 0;
            }
            else
              num = 1;
            flag1 = num != 0;
          }
          flag3 = this.Mission.MainAgent.MovementFlags.HasAnyFlag<Agent.MovementControlFlag>(Agent.MovementControlFlag.AttackMask);
        }
        return flag1 & flag2 & flag3;
      }
    }

    public Agent LockedAgent
    {
      get => this._lockedAgent;
      private set
      {
        if (this._lockedAgent == value)
          return;
        this._lockedAgent = value;
        MissionMainAgentController.OnLockedAgentChangedDelegate lockedAgentChanged = this.OnLockedAgentChanged;
        if (lockedAgentChanged == null)
          return;
        lockedAgentChanged(value);
      }
    }

    public Agent PotentialLockTargetAgent
    {
      get => this._potentialLockTargetAgent;
      private set
      {
        if (this._potentialLockTargetAgent == value)
          return;
        this._potentialLockTargetAgent = value;
        MissionMainAgentController.OnPotentialLockedAgentChangedDelegate lockedAgentChanged = this.OnPotentialLockedAgentChanged;
        if (lockedAgentChanged == null)
          return;
        lockedAgentChanged(value);
      }
    }

    public MissionMainAgentController()
    {
      this.InteractionComponent = new MissionMainAgentInteractionComponent(this);
      this.CustomLookDir = Vec3.Zero;
      this.IsChatOpen = false;
    }

    public override void EarlyStart()
    {
      base.EarlyStart();
      Game.Current.EventManager.RegisterEvent<MissionPlayerToggledOrderViewEvent>(new Action<MissionPlayerToggledOrderViewEvent>(this.OnPlayerToggleOrder));
      this.Mission.OnMainAgentChanged += new PropertyChangedEventHandler(this.Mission_OnMainAgentChanged);
      MissionMultiplayerGameModeBaseClient missionBehavior = this.Mission.GetMissionBehavior<MissionMultiplayerGameModeBaseClient>();
      if (missionBehavior?.RoundComponent != null)
      {
        missionBehavior.RoundComponent.OnRoundStarted += new Action(this.Disable);
        missionBehavior.RoundComponent.OnPreparationEnded += new Action(this.Enable);
      }
      ManagedOptions.OnManagedOptionChanged += new ManagedOptions.OnManagedOptionChangedDelegate(this.OnManagedOptionChanged);
      this.UpdateLockTargetOption();
    }

    public override void OnMissionScreenFinalize()
    {
      base.OnMissionScreenFinalize();
      this.Mission.OnMainAgentChanged -= new PropertyChangedEventHandler(this.Mission_OnMainAgentChanged);
      Game.Current.EventManager.UnregisterEvent<MissionPlayerToggledOrderViewEvent>(new Action<MissionPlayerToggledOrderViewEvent>(this.OnPlayerToggleOrder));
      MissionMultiplayerGameModeBaseClient missionBehavior = this.Mission.GetMissionBehavior<MissionMultiplayerGameModeBaseClient>();
      if (missionBehavior?.RoundComponent != null)
      {
        missionBehavior.RoundComponent.OnRoundStarted -= new Action(this.Disable);
        missionBehavior.RoundComponent.OnPreparationEnded -= new Action(this.Enable);
      }
      ManagedOptions.OnManagedOptionChanged -= new ManagedOptions.OnManagedOptionChangedDelegate(this.OnManagedOptionChanged);
    }

    public override bool IsReady()
    {
      bool flag = true;
      if (this.Mission.MainAgent != null)
        flag = this.Mission.MainAgent.AgentVisuals.CheckResources(true);
      return flag;
    }

    private void Mission_OnMainAgentChanged(object sender, PropertyChangedEventArgs e)
    {
      if (this.Mission.MainAgent == null)
        return;
      this._isPlayerAgentAdded = true;
      this._strafeModeActive = false;
      this._autoDismountModeActive = false;
    }

    public override void OnPreMissionTick(float dt)
    {
      base.OnPreMissionTick(dt);
      if (this.MissionScreen == null)
        return;
      if (this.Mission.MainAgent == null && GameNetwork.MyPeer != null)
      {
        MissionPeer component = GameNetwork.MyPeer.GetComponent<MissionPeer>();
        if (component != null)
        {
          if (component.HasSpawnedAgentVisuals)
            this.AgentVisualsMovementCheck();
          else if (component.FollowedAgent != null)
            this.RequestToSpawnAsBotCheck();
        }
      }
      Agent mainAgent = this.Mission.MainAgent;
      if ((mainAgent != null ? (mainAgent.State == AgentState.Active ? 1 : 0) : 0) != 0 && !this.MissionScreen.IsCheatGhostMode && !this.Mission.MainAgent.IsAIControlled && !this.IsDisabled && this._activated)
      {
        this.InteractionComponent.FocusTick();
        this.InteractionComponent.FocusedItemHealthTick();
        this.ControlTick();
        this.InteractionComponent.FocusStateCheckTick();
        this.LookTick(dt);
      }
      else
        this.LockedAgent = (Agent) null;
    }

    public override void OnAgentRemoved(
      Agent affectedAgent,
      Agent affectorAgent,
      AgentState agentState,
      KillingBlow blow)
    {
      if (this.InteractionComponent.CurrentFocusedObject != affectedAgent && affectedAgent != this.Mission.MainAgent)
        return;
      this.InteractionComponent.ClearFocus();
    }

    public override void OnAgentDeleted(Agent affectedAgent)
    {
      if (this.InteractionComponent.CurrentFocusedObject != affectedAgent)
        return;
      this.InteractionComponent.ClearFocus();
    }

    public override void OnClearScene() => this.InteractionComponent.OnClearScene();

    private void LookTick(float dt)
    {
      if (this.IsDisabled)
        return;
      Agent mainAgent = this.Mission.MainAgent;
      if (mainAgent == null)
        return;
      if (this._isPlayerAgentAdded)
      {
        this._isPlayerAgentAdded = false;
        mainAgent.LookDirectionAsAngle = mainAgent.MovementDirectionAsAngle;
      }
      if ((double) this.Mission.ClearSceneTimerElapsedTime < 0.0)
        return;
      Vec3 vec3;
      if (this.LockedAgent != null)
      {
        float num1 = 0.0f;
        float agentScale1 = this.LockedAgent.AgentScale;
        float agentScale2 = mainAgent.AgentScale;
        float num2 = this.LockedAgent.GetAgentFlags().HasAnyFlag<AgentFlag>(AgentFlag.IsHumanoid) ? (!this.LockedAgent.HasMount ? (this.LockedAgent.CrouchMode || this.LockedAgent.IsSitting() ? num1 + (this.LockedAgent.Monster.CrouchEyeHeight + 0.2f) * agentScale1 : num1 + (this.LockedAgent.Monster.StandingEyeHeight + 0.2f) * agentScale1) : num1 + (float) (((double) this.LockedAgent.MountAgent.Monster.RiderCameraHeightAdder + (double) this.LockedAgent.MountAgent.Monster.BodyCapsulePoint1.z + (double) this.LockedAgent.MountAgent.Monster.BodyCapsuleRadius) * (double) this.LockedAgent.MountAgent.AgentScale + (double) this.LockedAgent.Monster.CrouchEyeHeight * (double) agentScale1)) : num1 + this.LockedAgent.Monster.BodyCapsulePoint1.z * agentScale1;
        float valueTo = mainAgent.GetAgentFlags().HasAnyFlag<AgentFlag>(AgentFlag.IsHumanoid) ? (!mainAgent.HasMount ? (mainAgent.CrouchMode || mainAgent.IsSitting() ? num2 - (mainAgent.Monster.CrouchEyeHeight + 0.2f) * agentScale2 : num2 - (mainAgent.Monster.StandingEyeHeight + 0.2f) * agentScale2) : num2 - (float) (((double) mainAgent.MountAgent.Monster.RiderCameraHeightAdder + (double) mainAgent.MountAgent.Monster.BodyCapsulePoint1.z + (double) mainAgent.MountAgent.Monster.BodyCapsuleRadius) * (double) mainAgent.MountAgent.AgentScale + (double) mainAgent.Monster.CrouchEyeHeight * (double) agentScale2)) : num2 - this.LockedAgent.Monster.BodyCapsulePoint1.z * agentScale2;
        if (this.LockedAgent.GetAgentFlags().HasAnyFlag<AgentFlag>(AgentFlag.IsHumanoid))
          valueTo -= 0.3f * agentScale1;
        float z = MBMath.Lerp(this._lastLockedAgentHeightDifference, valueTo, MathF.Min(8f * dt, 1f));
        this._lastLockedAgentHeightDifference = z;
        vec3 = (this.LockedAgent.VisualPosition + (this.LockedAgent.MountAgent != null ? this.LockedAgent.MountAgent.GetMovementDirection().ToVec3() * this.LockedAgent.MountAgent.Monster.RiderBodyCapsuleForwardAdder : Vec3.Zero) + new Vec3(z: z) - (mainAgent.VisualPosition + (mainAgent.MountAgent != null ? mainAgent.MountAgent.GetMovementDirection().ToVec3() * mainAgent.MountAgent.Monster.RiderBodyCapsuleForwardAdder : Vec3.Zero))).NormalizedCopy();
      }
      else if (this.CustomLookDir.IsNonZero)
      {
        vec3 = this.CustomLookDir;
      }
      else
      {
        Mat3 identity = Mat3.Identity;
        identity.RotateAboutUp(this.MissionScreen.CameraBearing);
        identity.RotateAboutSide(this.MissionScreen.CameraElevation);
        vec3 = identity.f;
      }
      if (!this.MissionScreen.IsViewingCharacter() && !mainAgent.IsLookDirectionLocked && mainAgent.MovementLockedState != AgentMovementLockedState.FrameLocked)
        mainAgent.LookDirection = vec3;
      mainAgent.HeadCameraMode = this.Mission.CameraIsFirstPerson;
    }

    private void AgentVisualsMovementCheck()
    {
      if (!this.Input.IsGameKeyReleased(13))
        return;
      this.BreakAgentVisualsInvulnerability();
    }

    public void BreakAgentVisualsInvulnerability()
    {
      if (GameNetwork.IsClient)
      {
        GameNetwork.BeginModuleEventAsClient();
        GameNetwork.WriteMessage((GameNetworkMessage) new AgentVisualsBreakInvulnerability());
        GameNetwork.EndModuleEventAsClient();
      }
      else
        Mission.Current.GetMissionBehavior<SpawnComponent>().SetEarlyAgentVisualsDespawning(GameNetwork.MyPeer.GetComponent<MissionPeer>());
    }

    private void RequestToSpawnAsBotCheck()
    {
      if (!this.Input.IsGameKeyPressed(13))
        return;
      if (GameNetwork.IsClient)
      {
        GameNetwork.BeginModuleEventAsClient();
        GameNetwork.WriteMessage((GameNetworkMessage) new RequestToSpawnAsBot());
        GameNetwork.EndModuleEventAsClient();
      }
      else
      {
        if (!GameNetwork.MyPeer.GetComponent<MissionPeer>().HasSpawnTimerExpired)
          return;
        GameNetwork.MyPeer.GetComponent<MissionPeer>().WantsToSpawnAsBot = true;
      }
    }

    private Agent FindTargetedLockableAgent(Agent player)
    {
      Vec3 direction = this.MissionScreen.CombatCamera.Direction;
      Vec3 vec3_1 = direction;
      Vec3 position = this.MissionScreen.CombatCamera.Position;
      Vec3 visualPosition = player.VisualPosition;
      float num1 = new Vec3(position.x, position.y).Distance(new Vec3(visualPosition.x, visualPosition.y));
      Vec3 vec3_2 = position * (1f - num1) + (position + direction) * num1;
      float num2 = 0.0f;
      Agent agent1 = (Agent) null;
      foreach (Agent agent2 in (List<Agent>) this.Mission.Agents)
      {
        if (agent2.IsMount && agent2.RiderAgent != null && agent2.RiderAgent.IsEnemyOf(player) || !agent2.IsMount && agent2.IsEnemyOf(player))
        {
          Vec3 vec3_3 = agent2.GetChestGlobalPosition() - vec3_2;
          float x = vec3_3.Normalize();
          if ((double) x < 20.0)
          {
            float num3 = Vec2.DotProduct(vec3_1.AsVec2.Normalized(), vec3_3.AsVec2.Normalized());
            Vec2 asVec2 = vec3_1.AsVec2;
            Vec2 va = new Vec2(asVec2.Length, vec3_1.z);
            asVec2 = vec3_3.AsVec2;
            Vec2 vb = new Vec2(asVec2.Length, vec3_3.z);
            float num4 = Vec2.DotProduct(va, vb);
            if ((double) num3 > 0.949999988079071 && (double) num4 > 0.949999988079071)
            {
              float num5 = num3 * num3 * num3 / MathF.Pow(x, 0.15f);
              if ((double) num5 > (double) num2)
              {
                num2 = num5;
                agent1 = agent2;
              }
            }
          }
        }
      }
      return agent1 != null && agent1.IsMount && agent1.RiderAgent != null ? agent1.RiderAgent : agent1;
    }

    private void ControlTick()
    {
      if (this.MissionScreen != null && this.MissionScreen.IsPhotoModeEnabled || this.IsChatOpen)
        return;
      Agent mainAgent = this.Mission.MainAgent;
      bool flag1 = false;
      MissionWeapon wieldedWeapon;
      if (this.LockedAgent != null)
      {
        if (this.Mission.Agents.ContainsQ<Agent>(this.LockedAgent) && this.LockedAgent.IsActive() && (double) this.LockedAgent.Position.DistanceSquared(mainAgent.Position) <= 625.0 && !this.Input.IsGameKeyReleased(26) && !this.Input.IsGameKeyDown(25) && (this.Mission.Mode == MissionMode.Battle || this.Mission.Mode == MissionMode.Stealth))
        {
          wieldedWeapon = mainAgent.WieldedWeapon;
          if (!wieldedWeapon.IsEmpty)
          {
            wieldedWeapon = mainAgent.WieldedWeapon;
            if (wieldedWeapon.CurrentUsageItem.IsRangedWeapon)
              goto label_7;
          }
          if (this.MissionScreen != null && this.MissionScreen.GetSpectatingData(this.MissionScreen.CombatCamera.Frame.origin).CameraType == SpectatorCameraTypes.LockToMainPlayer)
            goto label_8;
        }
label_7:
        this.LockedAgent = (Agent) null;
        flag1 = true;
      }
label_8:
      if (this.Mission.Mode == MissionMode.Conversation)
      {
        mainAgent.MovementFlags = (Agent.MovementControlFlag) 0;
        mainAgent.MovementInputVector = Vec2.Zero;
      }
      else
      {
        if ((double) this.Mission.ClearSceneTimerElapsedTime < 0.0 || mainAgent.State != AgentState.Active)
          return;
        bool flag2 = false;
        bool flag3 = false;
        bool flag4 = false;
        bool flag5 = false;
        Vec2 vec2 = new Vec2(this.Input.GetGameKeyAxis("MovementAxisX"), this.Input.GetGameKeyAxis("MovementAxisY"));
        if (this._autoDismountModeActive)
        {
          if (!this.Input.IsGameKeyDown(0) && mainAgent.MountAgent != null)
          {
            if ((double) mainAgent.GetCurrentVelocity().y > 0.0)
              vec2.y = -1f;
          }
          else
            this._autoDismountModeActive = false;
        }
        if ((double) MathF.Abs(vec2.x) < 0.20000000298023224)
          vec2.x = 0.0f;
        if ((double) MathF.Abs(vec2.y) < 0.20000000298023224)
          vec2.y = 0.0f;
        if (vec2.IsNonZero())
        {
          float rotationInRadians = vec2.RotationInRadians;
          if ((double) rotationInRadians > -0.78539818525314331 && (double) rotationInRadians < 0.78539818525314331)
            flag3 = true;
          else if ((double) rotationInRadians < -2.3561944961547852 || (double) rotationInRadians > 2.3561944961547852)
            flag5 = true;
          else if ((double) rotationInRadians < 0.0)
            flag2 = true;
          else
            flag4 = true;
        }
        mainAgent.EventControlFlags = (Agent.EventControlFlag) 0;
        mainAgent.MovementFlags = (Agent.MovementControlFlag) 0;
        mainAgent.MovementInputVector = Vec2.Zero;
        if (!this.MissionScreen.IsRadialMenuActive && !this.Mission.IsOrderMenuOpen)
        {
          if (this.Input.IsGameKeyPressed(14))
          {
            if (mainAgent.MountAgent == null || (double) mainAgent.MovementVelocity.LengthSquared > 0.090000003576278687)
              mainAgent.EventControlFlags |= Agent.EventControlFlag.Jump;
            else
              mainAgent.EventControlFlags |= Agent.EventControlFlag.Rear;
          }
          if (this.Input.IsGameKeyPressed(13))
            mainAgent.MovementFlags |= Agent.MovementControlFlag.Action;
        }
        if (mainAgent.MountAgent != null && (double) mainAgent.GetCurrentVelocity().y < 0.5 && (this.Input.IsGameKeyDown(3) || this.Input.IsGameKeyDown(2)))
        {
          if (this.Input.IsGameKeyPressed(16))
            this._strafeModeActive = true;
        }
        else
          this._strafeModeActive = false;
        Agent.MovementControlFlag lastMovementKeyPressed = this._lastMovementKeyPressed;
        if (this.Input.IsGameKeyPressed(0))
          lastMovementKeyPressed = Agent.MovementControlFlag.Forward;
        else if (this.Input.IsGameKeyPressed(1))
          lastMovementKeyPressed = Agent.MovementControlFlag.Backward;
        else if (this.Input.IsGameKeyPressed(2))
          lastMovementKeyPressed = Agent.MovementControlFlag.StrafeLeft;
        else if (this.Input.IsGameKeyPressed(3))
          lastMovementKeyPressed = Agent.MovementControlFlag.StrafeRight;
        if (lastMovementKeyPressed != this._lastMovementKeyPressed)
        {
          this._lastMovementKeyPressed = lastMovementKeyPressed;
          Game.Current?.EventManager.TriggerEvent<MissionPlayerMovementFlagsChangeEvent>(new MissionPlayerMovementFlagsChangeEvent(this._lastMovementKeyPressed));
        }
        if (!this.Input.GetIsMouseActive())
        {
          bool flag6 = true;
          if (flag3)
            lastMovementKeyPressed = Agent.MovementControlFlag.Forward;
          else if (flag5)
            lastMovementKeyPressed = Agent.MovementControlFlag.Backward;
          else if (flag4)
            lastMovementKeyPressed = Agent.MovementControlFlag.StrafeLeft;
          else if (flag2)
            lastMovementKeyPressed = Agent.MovementControlFlag.StrafeRight;
          else
            flag6 = false;
          if (flag6)
            this.Mission.SetLastMovementKeyPressed(lastMovementKeyPressed);
        }
        else
          this.Mission.SetLastMovementKeyPressed(this._lastMovementKeyPressed);
        if (this.Input.IsGameKeyPressed(0))
        {
          if ((double) this._lastForwardKeyPressTime + 0.30000001192092896 > (double) Time.ApplicationTime)
          {
            mainAgent.EventControlFlags &= ~Agent.EventControlFlag.DoubleTapToDirectionMask;
            mainAgent.EventControlFlags |= Agent.EventControlFlag.DoubleTapToDirectionUp;
          }
          this._lastForwardKeyPressTime = Time.ApplicationTime;
        }
        if (this.Input.IsGameKeyPressed(1))
        {
          if ((double) this._lastBackwardKeyPressTime + 0.30000001192092896 > (double) Time.ApplicationTime)
          {
            mainAgent.EventControlFlags &= ~Agent.EventControlFlag.DoubleTapToDirectionMask;
            mainAgent.EventControlFlags |= Agent.EventControlFlag.DoubleTapToDirectionDown;
          }
          this._lastBackwardKeyPressTime = Time.ApplicationTime;
        }
        if (this.Input.IsGameKeyPressed(2))
        {
          if ((double) this._lastLeftKeyPressTime + 0.30000001192092896 > (double) Time.ApplicationTime)
          {
            mainAgent.EventControlFlags &= ~Agent.EventControlFlag.DoubleTapToDirectionMask;
            mainAgent.EventControlFlags |= Agent.EventControlFlag.DoubleTapToDirectionLeft;
          }
          this._lastLeftKeyPressTime = Time.ApplicationTime;
        }
        if (this.Input.IsGameKeyPressed(3))
        {
          if ((double) this._lastRightKeyPressTime + 0.30000001192092896 > (double) Time.ApplicationTime)
          {
            mainAgent.EventControlFlags &= ~Agent.EventControlFlag.DoubleTapToDirectionMask;
            mainAgent.EventControlFlags |= Agent.EventControlFlag.DoubleTapToDirectionRight;
          }
          this._lastRightKeyPressTime = Time.ApplicationTime;
        }
        if (this._isTargetLockEnabled)
        {
          if (this.Input.IsGameKeyDown(26) && this.LockedAgent == null && !this.Input.IsGameKeyDown(25) && (this.Mission.Mode == MissionMode.Battle || this.Mission.Mode == MissionMode.Stealth))
          {
            wieldedWeapon = mainAgent.WieldedWeapon;
            if (!wieldedWeapon.IsEmpty)
            {
              wieldedWeapon = mainAgent.WieldedWeapon;
              if (wieldedWeapon.CurrentUsageItem.IsRangedWeapon)
                goto label_88;
            }
            if (!GameNetwork.IsMultiplayer)
            {
              float applicationTime = Time.ApplicationTime;
              if ((double) this._lastLockKeyPressTime <= 0.0)
                this._lastLockKeyPressTime = applicationTime;
              if ((double) applicationTime > (double) this._lastLockKeyPressTime + 0.30000001192092896)
              {
                this.PotentialLockTargetAgent = this.FindTargetedLockableAgent(mainAgent);
                goto label_89;
              }
              else
                goto label_89;
            }
          }
label_88:
          this.PotentialLockTargetAgent = (Agent) null;
label_89:
          if (this.LockedAgent == null && !flag1 && this.Input.IsGameKeyReleased(26) && !GameNetwork.IsMultiplayer)
          {
            this._lastLockKeyPressTime = 0.0f;
            if (!this.Input.IsGameKeyDown(25) && (this.Mission.Mode == MissionMode.Battle || this.Mission.Mode == MissionMode.Stealth))
            {
              wieldedWeapon = mainAgent.WieldedWeapon;
              if (!wieldedWeapon.IsEmpty)
              {
                wieldedWeapon = mainAgent.WieldedWeapon;
                if (wieldedWeapon.CurrentUsageItem.IsRangedWeapon)
                  goto label_95;
              }
              if (this.MissionScreen != null && this.MissionScreen.GetSpectatingData(this.MissionScreen.CombatCamera.Frame.origin).CameraType == SpectatorCameraTypes.LockToMainPlayer)
                this.LockedAgent = this.FindTargetedLockableAgent(mainAgent);
            }
          }
        }
label_95:
        if (mainAgent.MountAgent != null && !this._strafeModeActive)
        {
          if (flag2 || (double) vec2.x > 0.0)
            mainAgent.MovementFlags |= Agent.MovementControlFlag.TurnRight;
          else if (flag4 || (double) vec2.x < 0.0)
            mainAgent.MovementFlags |= Agent.MovementControlFlag.TurnLeft;
        }
        mainAgent.MovementInputVector = vec2;
        if (!this.MissionScreen.MouseVisible && !this.MissionScreen.IsRadialMenuActive && !this._isPlayerOrderOpen && mainAgent.CombatActionsEnabled)
        {
          wieldedWeapon = mainAgent.WieldedWeapon;
          WeaponComponentData currentUsageItem1 = wieldedWeapon.CurrentUsageItem;
          bool flag7 = currentUsageItem1 != null && currentUsageItem1.WeaponFlags.HasAllFlags<WeaponFlags>(WeaponFlags.StringHeldByHand);
          wieldedWeapon = mainAgent.WieldedWeapon;
          WeaponComponentData currentUsageItem2 = wieldedWeapon.CurrentUsageItem;
          if ((currentUsageItem2 != null ? (currentUsageItem2.IsRangedWeapon ? 1 : 0) : 0) != 0)
          {
            wieldedWeapon = mainAgent.WieldedWeapon;
            0 = wieldedWeapon.CurrentUsageItem.IsConsumable ? 1 : 0;
          }
          wieldedWeapon = mainAgent.WieldedWeapon;
          WeaponComponentData currentUsageItem3 = wieldedWeapon.CurrentUsageItem;
          int num1;
          if ((currentUsageItem3 != null ? (currentUsageItem3.IsRangedWeapon ? 1 : 0) : 0) != 0)
          {
            wieldedWeapon = mainAgent.WieldedWeapon;
            if (!wieldedWeapon.CurrentUsageItem.IsConsumable)
            {
              wieldedWeapon = mainAgent.WieldedWeapon;
              num1 = !wieldedWeapon.CurrentUsageItem.WeaponFlags.HasAllFlags<WeaponFlags>(WeaponFlags.StringHeldByHand) ? 1 : 0;
              goto label_108;
            }
          }
          num1 = 0;
label_108:
          bool flag8 = num1 != 0;
          int num2 = (double) NativeOptions.GetConfig(NativeOptions.NativeOptionsType.EnableAlternateAiming) == 0.0 ? 0 : (flag7 | flag8 ? 1 : 0);
          if (num2 != 0)
            this.HandleRangedWeaponAttackAlternativeAiming(mainAgent);
          else if (this.Input.IsGameKeyDown(9))
            mainAgent.MovementFlags |= mainAgent.AttackDirectionToMovementFlag(mainAgent.GetAttackDirection());
          if (num2 == 0 && this.Input.IsGameKeyDown(10))
          {
            if ((double) ManagedOptions.GetConfig(ManagedOptions.ManagedOptionsType.ControlBlockDirection) == 2.0 && MissionGameModels.Current.AutoBlockModel != null)
            {
              switch (MissionGameModels.Current.AutoBlockModel.GetBlockDirection(this.Mission))
              {
                case Agent.UsageDirection.AttackUp:
                  mainAgent.MovementFlags |= Agent.MovementControlFlag.DefendUp;
                  break;
                case Agent.UsageDirection.AttackDown:
                  mainAgent.MovementFlags |= Agent.MovementControlFlag.DefendDown;
                  break;
                case Agent.UsageDirection.AttackLeft:
                  mainAgent.MovementFlags |= Agent.MovementControlFlag.DefendRight;
                  break;
                case Agent.UsageDirection.AttackRight:
                  mainAgent.MovementFlags |= Agent.MovementControlFlag.DefendLeft;
                  break;
              }
            }
            else
              mainAgent.MovementFlags |= mainAgent.GetDefendMovementFlag();
          }
        }
        if (this.MissionScreen.IsRadialMenuActive || this.Mission.IsOrderMenuOpen)
          return;
        if (this.Input.IsGameKeyPressed(16) && (mainAgent.KickClear() || mainAgent.MountAgent != null))
          mainAgent.EventControlFlags |= Agent.EventControlFlag.Kick;
        if (this.Input.IsGameKeyPressed(18))
          mainAgent.TryToWieldWeaponInSlot(EquipmentIndex.WeaponItemBeginSlot, Agent.WeaponWieldActionType.WithAnimation, false);
        else if (this.Input.IsGameKeyPressed(19))
          mainAgent.TryToWieldWeaponInSlot(EquipmentIndex.Weapon1, Agent.WeaponWieldActionType.WithAnimation, false);
        else if (this.Input.IsGameKeyPressed(20))
          mainAgent.TryToWieldWeaponInSlot(EquipmentIndex.Weapon2, Agent.WeaponWieldActionType.WithAnimation, false);
        else if (this.Input.IsGameKeyPressed(21))
          mainAgent.TryToWieldWeaponInSlot(EquipmentIndex.Weapon3, Agent.WeaponWieldActionType.WithAnimation, false);
        else if (this.Input.IsGameKeyPressed(11) && (double) this._lastWieldNextPrimaryWeaponTriggerTime + 0.20000000298023224 < (double) Time.ApplicationTime)
        {
          this._lastWieldNextPrimaryWeaponTriggerTime = Time.ApplicationTime;
          mainAgent.WieldNextWeapon(Agent.HandIndex.MainHand);
        }
        else if (this.Input.IsGameKeyPressed(12) && (double) this._lastWieldNextOffhandWeaponTriggerTime + 0.20000000298023224 < (double) Time.ApplicationTime)
        {
          this._lastWieldNextOffhandWeaponTriggerTime = Time.ApplicationTime;
          mainAgent.WieldNextWeapon(Agent.HandIndex.OffHand);
        }
        else if (this.Input.IsGameKeyPressed(23))
          mainAgent.TryToSheathWeaponInHand(Agent.HandIndex.MainHand, Agent.WeaponWieldActionType.WithAnimation);
        if (this.Input.IsGameKeyPressed(17) || this._weaponUsageToggleRequested)
        {
          mainAgent.EventControlFlags |= Agent.EventControlFlag.ToggleAlternativeWeapon;
          this._weaponUsageToggleRequested = false;
        }
        if (this.Input.IsGameKeyPressed(30))
          mainAgent.EventControlFlags |= mainAgent.WalkMode ? Agent.EventControlFlag.Run : Agent.EventControlFlag.Walk;
        if (mainAgent.MountAgent != null)
        {
          if (!this.Input.IsGameKeyPressed(15) && !this._autoDismountModeActive)
            return;
          if ((double) mainAgent.GetCurrentVelocity().y < 0.5 && mainAgent.MountAgent.GetCurrentActionType(0) != Agent.ActionCodeType.Rear)
          {
            mainAgent.EventControlFlags |= Agent.EventControlFlag.Dismount;
          }
          else
          {
            if (!this.Input.IsGameKeyPressed(15))
              return;
            this._autoDismountModeActive = true;
            mainAgent.EventControlFlags &= ~Agent.EventControlFlag.DoubleTapToDirectionMask;
            mainAgent.EventControlFlags |= Agent.EventControlFlag.DoubleTapToDirectionDown;
          }
        }
        else
        {
          if (!this.Input.IsGameKeyPressed(15))
            return;
          mainAgent.EventControlFlags |= mainAgent.CrouchMode ? Agent.EventControlFlag.Stand : Agent.EventControlFlag.Crouch;
        }
      }
    }

    private void HandleRangedWeaponAttackAlternativeAiming(Agent player)
    {
      if ((double) this.Input.GetKeyState(InputKey.ControllerLTrigger).x > 0.20000000298023224)
      {
        if ((double) this.Input.GetKeyState(InputKey.ControllerRTrigger).x < 0.60000002384185791)
          player.MovementFlags |= player.AttackDirectionToMovementFlag(player.GetAttackDirection());
        this._isPlayerAiming = true;
      }
      else
      {
        if (!this._isPlayerAiming)
          return;
        player.MovementFlags |= Agent.MovementControlFlag.DefendUp;
        this._isPlayerAiming = false;
      }
    }

    private void HandleTriggeredWeaponAttack(Agent player)
    {
      if ((double) this.Input.GetKeyState(InputKey.ControllerRTrigger).x > 0.20000000298023224)
      {
        if (!this._isPlayerAiming && player.WieldedWeapon.MaxAmmo > (short) 0 && player.WieldedWeapon.Ammo == (short) 0)
          player.MovementFlags |= player.AttackDirectionToMovementFlag(player.GetAttackDirection());
        else if (!this._playerShotMissile && (double) this.Input.GetKeyState(InputKey.ControllerRTrigger).x < 0.99000000953674316)
        {
          player.MovementFlags |= player.AttackDirectionToMovementFlag(player.GetAttackDirection());
          this._isPlayerAiming = true;
        }
        else
        {
          this._isPlayerAiming = true;
          this._playerShotMissile = true;
        }
      }
      else
      {
        if (!this._isPlayerAiming)
          return;
        this._playerShotMissile = false;
        this._isPlayerAiming = false;
        player.MovementFlags |= Agent.MovementControlFlag.DefendUp;
      }
    }

    public override bool IsThereAgentAction(Agent userAgent, Agent otherAgent)
    {
      return otherAgent.IsMount && otherAgent.IsActive();
    }

    public void Disable() => this._activated = false;

    public void Enable() => this._activated = true;

    private void OnPlayerToggleOrder(MissionPlayerToggledOrderViewEvent obj)
    {
      this._isPlayerOrderOpen = obj.IsOrderEnabled;
    }

    public void OnWeaponUsageToggleRequested() => this._weaponUsageToggleRequested = true;

    private void OnManagedOptionChanged(ManagedOptions.ManagedOptionsType optionType)
    {
      if (optionType != ManagedOptions.ManagedOptionsType.LockTarget)
        return;
      this.UpdateLockTargetOption();
    }

    private void UpdateLockTargetOption()
    {
      this._isTargetLockEnabled = (double) ManagedOptions.GetConfig(ManagedOptions.ManagedOptionsType.LockTarget) == 1.0;
      this.LockedAgent = (Agent) null;
      this.PotentialLockTargetAgent = (Agent) null;
      this._lastLockKeyPressTime = 0.0f;
      this._lastLockedAgentHeightDifference = 0.0f;
    }

    public delegate void OnLockedAgentChangedDelegate(Agent newAgent);

    public delegate void OnPotentialLockedAgentChangedDelegate(Agent newPotentialAgent);
  }
}
